<script setup>
// 引用区域
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDeptListApi,
  addDeptApi,
  queryByIdApi,
  updateByIdApi,
  deleteByIdApi,
} from "@/api/dept.js";
//数据结构体区域
const deptList = ref([]);
const dialogFormVisible = ref(false);
const dept = ref({ name: "" });
const formLabelWidth = "100px";
const form_title = ref("");
const rules = ref({
  name: [
    { required: true, message: "部门名称是必填项", trigger: "blur" }, //必填项
    {
      min: 2,
      max: 10,
      message: "部门名称长度在 2 到 10 个字符",
      trigger: "blur",
    }, //
  ],
});
const deptRuleForm = ref();
//方法区域
// （老方法  axios ）
// const search = async () => {
//   const result = await axios.get("http://127.0.0.1:8080/depts");
//   if (result.data.code) {
//     //JS隐式类型转换false,其他数字true:其他都是true；null,undefined --false
//     deptList.value = result.data.data;
//   }
// };

//新方法
const search = async () => {
  const result = await getDeptListApi();
  if (result.code) {
    //JS隐式类型0转换false,其他数字true:其他都是true；null,undefined --false
    deptList.value = result.data;
  }
};

// 点击新增部门按钮事件
const save = () => {
  console.log("save!");
  dialogFormVisible.value = true;
  form_title.value = "新增部门";
  //清理上次遗留的对象 重置
  dept.value = {};
  //清空上次遗留的校验规则
  if (deptRuleForm.value) {
    deptRuleForm.value.resetFields();
  }
};
const submit = async () => {
  //表单校验  未获取到表单对象 return
  if (!deptRuleForm.value) {
    return;
  }
  // 获取表单对象
  deptRuleForm.value.validate(async (valid) => {
    if (valid) {
      console.log("submit!");
      let result;
      if (dept.value.id) {
        //有id执行修改
        result = await updateByIdApi(dept.value);
      } else {
        //无id执行新增
        result = await addDeptApi(dept.value);
      }
      if (result.code) {
        //提示信息
        console.log("success");
        // alert("新增成功");   //alert有阻塞效果 不操作 下列语句都不会进行
        PromptSuccess("新增成功");
        dialogFormVisible.value = false;
        search();
      } else {
        console.log("error");
        PromptFail(result.msg);
      }
    } else {
      PromptFail("新增部门表单校验失败");
    }
  });
};

const editOpen = async (id) => {
  console.log("edit!");
  form_title.value = "修改部门";
  //清空上次遗留的校验规则
  if (deptRuleForm.value) {
    deptRuleForm.value.resetFields();
  }
  const result = await queryByIdApi(id);
  if (result.code) {
    dialogFormVisible.value = true;
    //JS隐式类型转换false,其他数字true:其他都是true；null,undefined --false
    dept.value = result.data;
  }
};

const delById = async (id) => {
  //弹出消息确认框
  ElMessageBox.confirm("请确认是否删除?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }) //点击确认 then
    .then(async () => {
      //删除
      const result = await deleteByIdApi(id);
      if (result.code) {
        //提示结果
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        //回调查询方法
        search();
      } else {
        ElMessage({
          type: "error",
          message: result.msg,
        });
      }
    }) //点击取消
    .catch(() => {
      ElMessage({
        type: "info",
        message: "您以取消删除",
      });
    });
};
//消息提示
const PromptSuccess = (message) => {
  ElMessage({
    message: message,
    type: "success",
  });
};

const PromptFail = (message) => {
  ElMessage.error(message);
};

//钩子函数区域
onMounted(() => {
  search();
});
</script>

<template>
  <!-- 按钮区域  start -->
  <div class="placeholder">&nbsp;</div>
  <h1 class="inline-title">&nbsp;&nbsp;&nbsp;部门管理</h1>
  <div class="container">
    <el-button type="primary" @click="save">新增部门</el-button>
  </div>
  <!-- 按钮区域  end -->

  <!-- 表格区域start -->
  <div class="deptListTable">
    <el-table :data="deptList" border style="width: 80%">
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column
        prop="name"
        label="部门名称"
        width="180"
        align="center"
      />
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="360"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editOpen(scope.row.id)"
            ><el-icon> <EditPen /> </el-icon>编辑</el-button
          >
          <el-button type="danger" size="small" @click="delById(scope.row.id)"
            ><el-icon> <Delete /> </el-icon>删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 表格区域end -->
  <!-- 对话框区域 start -->
  <!--dialogFormVisible 属性为 true  则展示  -->
  <div>
    <el-dialog v-model="dialogFormVisible">
      <div class="boldTitle">
        <div class="placeholder">&nbsp;</div>
        {{ form_title }}
      </div>
      <!-- 测试使用 非测试禁止打开 {{ dept }} -->
      <el-form :model="dept" :rules="rules" ref="deptRuleForm">
        <el-form-item
          label="部门名称："
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="dept.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <!-- 对话框区域 end -->
</template>

<style scoped>
.boldTitle {
  font-weight: bold;
  font-size: 20px;
  margin-top: 0px;
  margin-bottom: 30px;
}
.deptListTable {
  margin: 20px 0px;
}

.container {
  margin: 6px 0px;
}

.placeholder {
  width: 5px;
  height: auto;
  background-color: blue;
  display: inline-block;
}

.inline-title {
  display: inline-block;
}
</style>
